package com.mediacloud.app.newsmodule.activity;


import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.jaeger.library.StatusBarUtil;
import com.lzf.easyfloat.interfaces.OnPermissionResult;
import com.lzf.easyfloat.permission.PermissionUtils;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.IntegralConfig;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoVodDetailFragment;
import com.mediacloud.app.newsmodule.model.CommentListDataReciver;
import com.mediacloud.app.newsmodule.model.NewsCommentItem;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.CommentListDataInvoker;
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.newsmodule.utils.share.IShareWrap;
import com.mediacloud.app.newsmodule.utils.share.OnScreenShotListener;
import com.mediacloud.app.newsmodule.utils.share.PosterShareWrap;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.utils.ClickUtils;
import com.utils.DeviceUtils;
import com.utils.NetUtils;
import com.utils.UriTool;
import com.utils.read.AudioFloatManager;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.utils.FrameBimapKit;
import com.yoake.media.player.utils.OnPlayerActionListener;
import com.yoake.media.player.utils.VirtualDanmakuKit;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;
import com.yoake.media.player.utils.XVideoSpeed;
import com.yoake.media.player.utils.cache.XPlayerPreloadManager;
import com.yoake.media.player.utils.interfaces.PendingPlayerChangeListener;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;

/**
 * 视频点播
 * 视频类型详情页
 */
@SuppressWarnings("ALL")
public class VideoVodDetailActivity extends StyleSetActivity implements OnScreenShotListener {
    protected boolean isAutoPlay = true;
    public XPlayer mBaiduPlayer;
    VideoVodDetailFragment fragment;
    private Long launchTimeLong = 0L;


    ShowSwitch showSwitch;

    //支付相关
    LinearLayout broccoliLayout;
    View vodBottomContent;

    // private TextView emptyTipsText;

    long mTyReportStartTime = 0;
    long mTyReportEndTime = 0;

    protected CommentListDataInvoker commentListInvoker;
    protected CommentListCallBack mCommentListCallBack;
    public static final long startPosition = 0L;
    public static final long stopPosition=0L;
    public static final long dragBeforePosition=0L;
    public static final long  dragAfterPosition = 0L;
    public static final long  videoDuration = 0L;
    private boolean isForwardComplate = false;
    private boolean isCompleted = false;

    @Override
    public boolean showTitleBar() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCommentDialog = true;
        super.onCreate(savedInstanceState);

        Uri uriData = getIntent().getData();
        if (uriData != null) {
            isFromH5OpenToReStart = UriTool.INSTANCE.isFromH5OpenToReStart(this, uriData);
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            catalogItem = getIntent().getParcelableExtra("catalog");
            articleItem = getIntent().getParcelableExtra("data");
            if (articleItem == null) {
                articleItem = ArticleItem.praseIntentDataToArticleItem(getIntent(), TypeX.NEWS.VIDEO);
            }
        }
        if (articleItem != null) {
            showSwitch = articleItem.getmShowSwitch();
        }
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
        }
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        if (retryTips != null) {
            retryTips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    if (hasNetWork) {
                        if (currentState != TYPE_LOADING) {
                            showStateView(TYPE_LOADING, false);
                            getVideoDetail();
                        }
                    } else {
                        showNetWorDialog();
                    }
                }
            });
        }

        if (loadingView != null) {
            loadingView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClickUtils.delayClickable(v);
                    if (hasNetWork) {
                        if (currentState != TYPE_LOADING) {
                            showStateView(TYPE_LOADING, false);
                            getVideoDetail();
                        }
                    } else {
                        showNetWorDialog();
                    }


                }
            });
        }
        vodBottomContent = Utility.findViewById(mRootView, R.id.vodBottomContent);
        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
        boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(serverAppConfigInfo.getContent_list());
        if (isLeftImgMode) {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
            }
        }
        mBaiduPlayer = Utility.findViewById(mRootView, R.id.mBaiduPlayer);
        mBaiduPlayer.getController().getControllerInstance().setEnableOrientation(true);
        mBaiduPlayer.setRelease(false);
        mBaiduPlayer.getPrepareView().setVisibleThumb(false);
        mBaiduPlayer.getCompleteView().setVisibleThumb(false);
        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if (!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)) {
            mBaiduPlayer.getTitleView().hideTitleMoreView();
            mBaiduPlayer.getErrorView().hideTitleMoreView();
        }
        if (DeviceUtils.isCus(this)) {
            mBaiduPlayer.setPlayerFactory(ExoMediaPlayerFactory.create());
        }
        //  mBaiduPlayer.setDebug(true);
        // mBaiduPlayer.setSpecial(true);
        mBaiduPlayer.setPendingSeek(VideoSeekKit.getHisSeek("" + articleItem.getId()));
        if (!TextUtils.isEmpty(articleItem.getLogo())) {
            mBaiduPlayer.setPoster(ImageKitKt.buildUrl(3, articleItem.getLogo()), ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img));
        }
        if (DeviceUtils.isCus(this)) {
            mBaiduPlayer.showSwitchAudioBtn();
            mBaiduPlayer.setDanmukuSwitchViewState(true, true);
            setTestDanma();//鲜产品说放开
        } else {
            mBaiduPlayer.hideDanMu();
        }
        //虚拟弹幕

        tvLetmeSay.setText("我来说几句");
//           setTestDanma();

        //   mBaiduPlayer.setPoster("https://image.demo.chinamcloud.cn/0/b81ab1497ae1133dbc41e584912d77aa/Pic/2022/02/20/de88517aefd04dfd8f1eed600bc597e1_2000k.jpg", AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);

        //emptyTipsText = Utility.findViewById(mRootView, R.id.emptyTipsText);
//        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        setPlayerView();


        if (articleItem == null)
            return;
        fragment = new VideoVodDetailFragment();

        if (isAutoPlay)
            KillMusicUtils.stopAPS(this);
        getVideoDetail();

        setNewsTitle();

        onPageStart();
        showPageTransition();
        //设置使用刘海屏幕区域
        new DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES);

        if (DeviceUtils.isCus(this)) {
            getCommentData();
        }
        judgeInteval();

        AddMedalStatistics.addMedalStatistics(this);//勋章统计


        if (!NetUtils.isNetConnection(this)) {
            ArticleItemReciver articleItemReciver = new ArticleItemReciver();
            articleItemReciver.articleItem = articleItem;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }
            initDetailFragment(articleItemReciver, true);
            hiddBroccoliLayout();
            setVideoContent(articleItem.getVideo());
        }

    }

    IntegralConfig config;
    boolean openInteval = false;//是否开启积分任务
    //    boolean openGrow = false;//是否开启成长值任务
    int timeInteval = 0;//增加积分时间（分）
//    int timeGrow = 0;//增加成长值时间（分）

    //判断是否开启积分和无和成长任务
    private void judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig;
        if (config != null) {
            if (config.enableList1 != null && config.enableList1.size() != 0) {
                for (int i = 0; i < config.enableList1.size(); i++) {
                    if (config.enableList1.get(i) == 8) {
                        openInteval = true;
                        timeInteval = config.videoLeastDuration1;
                    }
                }
            }

            /*if (config.enableList4 != null && config.enableList4.size() != 0) {
                for (int i = 0; i < config.enableList4.size(); i++) {
                    if (config.enableList4.get(i) == 8) {
                        openGrow = false;
                        timeGrow = config.videoLeastDuration4;
                    }
                }
            }*/
        }
    }


    private void getCommentData() {
        mCommentListCallBack = new CommentListCallBack();
        commentListInvoker = new CommentListDataInvoker(mCommentListCallBack);
        commentListInvoker.getAllCommentList(1, articleItem.getId() + "", UserInfo.getUserInfo(this).getUserid());
    }

    @Override
    public void onScreenShot() {
        if (mBaiduPlayer.isFullScreen()) {
            mBaiduPlayer.getController().toggleFullScreen();
            mBaiduPlayer.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        Bitmap bitmap = mBaiduPlayer.doScreenShot();
                        IShareWrap iShareWrap = shareWrap.getShare();

                        shareWrap.show(mRootView);
                        if (iShareWrap instanceof PosterShareWrap) {
                            ((PosterShareWrap) iShareWrap).sharScreenShot(bitmap);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, 400);

        }
    }

    class CommentListCallBack implements DataInvokeCallBack<CommentListDataReciver> {

        @Override
        public void success(CommentListDataReciver data) {
            if (data.state) {
                if (data.commentList != null && data.commentList.size() != 0) {
                    setDanma(data.commentList);
                }
            }
        }

        @Override
        public void fault(Object data) {

        }
    }

    private void setDanma(List<NewsCommentItem> commentList) {
        VirtualDanmakuKit kit = new VirtualDanmakuKit(this, mBaiduPlayer);
        for (int i = 0; i < commentList.size(); i++) {
            kit.addDanma(commentList.get(i).getContent(), false);
        }
    }


    private void setTestDanma() {
        VirtualDanmakuKit kit = new VirtualDanmakuKit(this, mBaiduPlayer);
        kit.addDanma("中国，你是我的骄傲", false);
        kit.addDanma("厉害了我的国", false);
        kit.addDanma("人民的国家，伟大的民族", false);
        kit.addDanma("中国有力量，人民有信仰", false);
        kit.addDanma("很庆幸生活在一个和平伟大的年代，感谢祖国感谢党", false);
        kit.addDanma("致敬", false);
        kit.addDanma("致敬", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("致敬", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("致敬", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("祝福祖国", false);
        kit.addDanma("致敬", false);

    }


    //开启语音播报
    private void startReadNews() {
        if (TextUtils.isEmpty(lastPlayUrl)) {
            return;
        }
        TXReportManager.getInstance().voice_read(articleItem);
        articleItem.setText_audio_url(lastPlayUrl);
        MusicEntity musicEntity = new MusicEntity("" + articleItem.getTitle(), lastPlayUrl);
        APSHelper.play(this, "" + articleItem.getId(), musicEntity, mBaiduPlayer.getCurrentPosition());
        AudioFloatManager.Companion.getInstance(this).setArticle(articleItem);
        AudioFloatManager.Companion.getInstance(this).setCatalogItem(catalogItem);
        AudioFloatManager.Companion.getInstance(this).show();

    }

    public ShareWrap shareWrap;//播放器更多

    /**
     * 设置视频view
     */
    private void setPlayerView() {

        mBaiduPlayer.setAutoPlay(isAutoPlay);
        ViewGroup.LayoutParams layoutParams = mBaiduPlayer.getLayoutParams();
        float num = (float) (16.0 / 9.0);
        layoutParams.height = (int) (getResources().getDisplayMetrics().widthPixels / num);
        mBaiduPlayer.setLayoutParams(layoutParams);
        mBaiduPlayer.setOnTitleMoreClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mBaiduPlayer.isFullScreen()) {
                        mBaiduPlayer.getController().getControllerInstance().hide();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                shareWrap = new ShareWrap(VideoVodDetailActivity.this, false);
                shareWrap.setShowFunction(true);
                shareWrap.init(articleItem, new CatalogItem());
                ((PosterShareWrap) shareWrap.getShare()).setOnScreenShotListener(VideoVodDetailActivity.this);
                shareWrap.show(mRootView);
            }
        });
    }

    public ArticleItem getArticleItem() {
        return articleItem;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return true;
    }


    protected void setNewsTitle() {
        int base = serverAppConfigInfo.getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }

    }


    @Override
    public void onBackPressed() {

        boolean value = false;
        if (mBaiduPlayer != null && mBaiduPlayer.isFullScreen()) {
            mBaiduPlayer.onBackPressed();
            value = true;
        }
        if (shareWrap != null) {
            if (shareWrap.isShowing()) {
                shareWrap.dismiss();
                value = true;
            }
        }

        if (value)
            return;
        super.onBackPressed();

    }


    private boolean isGoOtherPage = false;
    /**
     * pause前是暂停的 回到页面不恢复播放
     */
    boolean isPlayBeforePause = false;

    @Override
    protected void onPause() {
        isPlayBeforePause = mBaiduPlayer != null && mBaiduPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PAUSED;
        super.onPause();
        if (mBaiduPlayer != null && !isFinish) {
            isGoOtherPage = true;
            saveViewHistory();
            if (commentIsOpen) {
                commentIsOpen = false;
                if (mBaiduPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PLAYING
                        || mBaiduPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARING
                        || mBaiduPlayer.getPlayStateAtLifecycleOwnerPause() == VideoView.STATE_PREPARED) {
                    mBaiduPlayer.start();
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void restorePause(NotifyMicroEvent event) {
        //防止点击home键，评论框pause了，视频也应该pause
        if (mBaiduPlayer != null) {
            if (event.getPlay()) {
                if (!isPlayBeforePause)
                    mBaiduPlayer.resume();
            } else {
                mBaiduPlayer.pause();
            }

        }
    }


    /**
     * 这里真实的去finish() 用于
     * 处理退出当前也没的时候，需要申请悬浮窗权限的时候，不能真实的调用finish()否则取不到权限申请的结果
     */
    public void realFinish() {
        super.finish();
        articleItem.setPreview(articleItem.getTitle());
        CDPTrackReportManager.getInstance().ProgramEndPlay(articleItem,mBaiduPlayer.getDuration()/1000,0,
                0,null,(mBaiduPlayer.getCurrentPosition()-startPosition)/1000);
        if (!TextUtils.isEmpty(MediaAuthorDetailActivity.intentId))
            CDPTrackReportManager.getInstance().DistrictCMContentDetailView(articleItem,((System.currentTimeMillis() - inTime) / 1000));
//        onVideoPlayEndEvent();
        else
            CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,mBaiduPlayer.getCurrentPosition()/1000);
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;

        if (mBaiduPlayer != null) {
            saveViewHistory();
        }
        try {
            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(fragment);
                transaction.commitNowAllowingStateLoss();
            }
        } catch (Exception ex) {
        }
        if (mBaiduPlayer != null) {
            FrameBimapKit frameBimapKit = mBaiduPlayer.getFrameBimapKit();
            if (frameBimapKit != null) {
                frameBimapKit.cancelTask();
                getLifecycle().removeObserver(frameBimapKit);
                Field contextField = null;
                try {
                    contextField = FrameBimapKit.class.getDeclaredField("context");
                    contextField.setAccessible(true);
                    contextField.set(frameBimapKit, null);
                } catch (Exception ignore) {
                }
            }

            mBaiduPlayer.release();
        }
    }

    @Override
    public void finish() {
        ReportKit.INSTANCE.escalationArticleTime();
        // super.finish();
        if (mBaiduPlayer != null && mBaiduPlayer.isPlaying() && mBaiduPlayer.isAudioPlay()) {
            if (PermissionUtils.checkPermission(this)) {
                startReadNews();
                realFinish();
            } else {
                AudioFloatManager.showPermissionAsk(this, new OnPermissionResult() {
                    @Override
                    public void permissionResult(boolean isOpen) {
                        if (isOpen) {
                            startReadNews();
                        }
                        realFinish();
                    }
                });
            }
        } else {
            realFinish();
        }

    }

    @Override
    public int getStatusBarColor() {
        return Color.BLACK;
    }

    @Override
    public boolean getBarTextColorIsDefault() {
        return false;
    }

    @Override
    public void refreshStatusBarColor() {
        StatusBarUtil.setColorNoTranslucent(this, Color.BLACK);
        StatusBarUtil.setDarkMode(this);
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_videovod_detail;
    }


    public void setVideoPlayerData() {

        mBaiduPlayer.getBottomControl().setPendingPlayerChangeListener(new PendingPlayerChangeListener() {
            @Override
            public void onPendingPlayerStateChange() {
                color(null);
            }
        });
        mBaiduPlayer.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
                if (playerState == VideoView.STATE_PAUSED) {

                }
            }

            @Override
            public void onPlayStateChanged(int playState) {
                try {
                    if (playState == VideoView.STATE_PAUSED) {
                        stopPosition = mBaiduPlayer.getCurrentPosition();
                        if (!TextUtils.isEmpty(MMKV.defaultMMKV().decodeString("127Title")))//来自视频合集
                            CDPTrackReportManager.getInstance().ProgramEndPlay(articleItem,mBaiduPlayer.getDuration()/1000,MMKV.defaultMMKV().decodeInt("current_episode"),
                                    MMKV.defaultMMKV().decodeInt("program_episode"),MMKV.defaultMMKV().decodeString("127Title"),(stopPosition-startPosition)/1000);
                        else{
                            CDPTrackReportManager.getInstance().ProgramEndPlay(articleItem,mBaiduPlayer.getDuration()/1000,0,
                                   0,null,(stopPosition-startPosition)/1000);
                        }
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("停止播放视频",
                                (isCompleted) ? "是" : "否",
                                String.valueOf((stopPosition - startPosition)/1000),
                                articleItem,
                                0,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                PlayerUtils.stringForTime((int) startPosition),
                                null,
                                PlayerUtils.stringForTime((int) stopPosition));
                    } else if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                        if (!isFinish) {
                            deleteHistoryPosition();
                        }
                        isCompleted = true;
                        CDPTrackReportManager.getInstance().ProgramEndPlay(articleItem,mBaiduPlayer.getDuration()/1000,0,
                                0,null,mBaiduPlayer.getCurrentPosition()/1000);
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("播完视频",
                                "是",
                                String.valueOf((videoDuration - startPosition)/1000), articleItem);

                    } else if (playState == VideoView.STATE_PLAYING) {
                        startPosition = mBaiduPlayer.getCurrentPosition();
                        videoDuration = mBaiduPlayer.getDuration();
                        if (!TextUtils.isEmpty(MMKV.defaultMMKV().decodeString("127Title")))//来自视频合集
                            CDPTrackReportManager.getInstance().ProgramStartPlay(articleItem,mBaiduPlayer.getDuration()/1000,MMKV.defaultMMKV().decodeInt("current_episode"),
                                    MMKV.defaultMMKV().decodeInt("program_episode"),MMKV.defaultMMKV().decodeString("127Title"));
                        else{
                            CDPTrackReportManager.getInstance().ProgramStartPlay(articleItem,mBaiduPlayer.getDuration()/1000,0,
                                    0,null);
                        }
                        TXReportManager.getInstance().app_jhapp_content_detail_interact("开始播放视频",
                                null,
                                null, articleItem
                                ,0,null, PlayerUtils.stringForTime((int) startPosition));
                    } else if (playState == VideoView.STATE_BUFFERED) {
//                        startPosition = mBaiduPlayer.getCurrentPosition();
                        dragAfterPosition = mBaiduPlayer.getCurrentPosition();
                        TXReportManager.getInstance().app_jhapp_content_detail_interact(isForwardComplate ? "拖动视频进度条（快进）" :"拖动视频进度条（快退）",
                                null,
                                null,
                                articleItem,
                                0,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                PlayerUtils.stringForTime((int) dragBeforePosition),
                                PlayerUtils.stringForTime((int) dragAfterPosition));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mBaiduPlayer.setOnPlayerActionListener(new OnPlayerActionListener() {
            @Override
            public void onProjectionScreen() {
                //投屏回调
                TXReportManager.getInstance().app_jhapp_content_detail_interact("点击投屏",
                        null,
                        null,
                        articleItem);
            }

            @Override
            public void onSpeedChange(@Nullable XVideoSpeed before, @NonNull XVideoSpeed after) {
                TXReportManager.getInstance().app_jhapp_content_detail_interact("切换倍速",
                        null,
                        null,
                        articleItem,
                        0,
                        null,
                        null,
                        null,
                        null,
                        before.getTitle(),
                        after.getTitle());
            }

            @Override
            public void onBitRateChange(@Nullable XVideoBitRate before, @NonNull XVideoBitRate after) {
                TXReportManager.getInstance().app_jhapp_content_detail_interact("切换码率",
                        null,
                        null,
                        articleItem,
                        0,
                        null,
                        null,
                        before.getTitle(),
                        after.getTitle());
            }

            @Override
            public void onDamuSwitch(boolean isOpen) {
                if (isOpen) {

                } else {

                }
            }

            @Override
            public void onPlayerStateChanged(int playerState) {
                boolean isFullScreen = playerState == VideoView.PLAYER_FULL_SCREEN;
                if (isFullScreen) {
                    TXReportManager.getInstance().app_jhapp_content_detail_interact("最大化视频窗口",
                           null,
                            null,
                            articleItem);
                }
            }

            @Override
            public void onSeekTo(boolean isForward) {
                dragBeforePosition = mBaiduPlayer.getCurrentPosition();
                isForwardComplate = isForward;
            }
        });
//        mBaiduPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
//            @Override
//            public void onpause(int currentMediaIndex) {
//                super.onpause(currentMediaIndex);
//                if (pauseAd != null)
//                    mBaiduPlayer.showAdPausevertiseView(pauseAd);
//                ReportManager.getInstance().pause_play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                        articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor(),currentMediaIndex+"");
//
//            }
//
//            @Override
//            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
//                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
////                DisplayCutoutManager dcm = new DisplayCutoutManager(VideoVodDetailActivity.this);
////
////
//                if (isFullScreen) {
//                    vodBottomContent.setVisibility(View.GONE);
//                    bottomBarLayout.setVisibility(View.GONE);
//                    ReportManager.getInstance().fullscreen_play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                            articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor(),currentMediaIndex+"");
//                } else {
//                    vodBottomContent.setVisibility(View.VISIBLE);
//                    bottomBarLayout.setVisibility(View.VISIBLE);
//                }
////                    mTitileBar.setVisibility(View.GONE);
////                    findViewById(R.id.vodBottomContent).setVisibility(View.GONE);
////                    if (dcm.isCutoutScreen()) {//用于处理华为刘海屏不能全屏到问题
////                        mBaiduPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE |
////                                View.SYSTEM_UI_FLAG_FULLSCREEN |
////                                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
////                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
////                    }
////                } else {
////                    findViewById(R.id.vodBottomContent).setVisibility(View.VISIBLE);
////                    mTitileBar.setVisibility(View.VISIBLE);
////                    if (dcm.isCutoutScreen()) {//刘海屏处理
////
////                        mBaiduPlayer.setSystemUiVisibility(0);
////                    }
////                }
//            }
//
//            @Override
//            public void oncomplete(int currentMediaIndex) {
//                super.oncomplete(currentMediaIndex);
//                seekTime = 0;
//                if (!isFinish)
//                    deleteHistoryPosition();
//            }
//
//            @Override
//            public void onstop(int currentMediaIndex) {
//                super.onstop(currentMediaIndex);
//                if (!isFinish)
//                    deleteHistoryPosition();
//            }
//
//            @Override
//            public void onPrepared(int currentMediaIndex) {
//                super.onPrepared(currentMediaIndex);
//                mBaiduPlayer.toggleFullScreenEnable(true);
//                ReportManager.getInstance().play_video(articleItem.getVid(),articleItem.getType()+"",articleItem.getId()+"",articleItem.getTitle(),
//                        articleItem.getId()+"",articleItem.getTitle(),articleItem.getReferName(),articleItem.getAuthor(),articleItem.getAuthor());
//                KillMusicUtils.stopAudioPlay(VideoVodDetailActivity.this);
//                try {
//                    String[] times = articleItem.getProp4().split(":");
//                    int hours, min, sec;
//                    hours = Integer.valueOf("" + times[0]);
//                    min = Integer.valueOf("" + times[1]);
//                    sec = Integer.valueOf("" + times[2]);
//                    int total = hours * 60 * 60;
//                    total += min * 60;
//                    total += sec;
//                    if (total > 0)
//                        mBaiduPlayer.setConfigDuration(total);
//                } catch (Exception e) {
//                    // TODO: handle exception
//                }
//                if (seekTime > 0) {
//                    mBaiduPlayer.post(() -> {
//                        if (seekTime >= mBaiduPlayer.getDuration())
//                            return;
//                        mBaiduPlayer.seek(seekTime);
//                        String seek_last_position_tips = getResources().getString(R.string.seek_last_position_tips);
//                        seek_last_position_tips += Tools.convertTimeFormat((int) seekTime);
//                        seekTime = 0;
//                        if (!isOutView)
//                            ToastUtil.show(VideoVodDetailActivity.this, seek_last_position_tips, Gravity.CENTER);
//                    });
//                } else {
//                    if (isOutView)
//                        stopShareBgPlayBug();
//                }
//            }
//
//            @Override
//            public void onSeekComplete(int currentMediaIndex) {
//                super.onSeekComplete(currentMediaIndex);
//                if (isOutView)
//                 stopShareBgPlayBug();
//                seekTime = 0;
//            }
//
//            @Override
//            public void onVideoComletionAd() {
//                super.onVideoComletionAd();
//            }
//        });
    }

//    protected final void stopShareBgPlayBug() {
//        mRootView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (isOutView && mBaiduPlayer != null)
//                    mBaiduPlayer.pause();
//            }
//        }, 500);
//    }

    protected void deleteHistoryPosition() {
        VideoSeekKit.clearHisSeek("" + articleItem.getId());
    }

    public void saveViewHistory() {
        if (mBaiduPlayer != null) {
            if (mBaiduPlayer.getCurrentPlayState() == VideoView.STATE_PLAYBACK_COMPLETED) {
                deleteHistoryPosition();
            } else if (mBaiduPlayer.getCurrentPosition() > 0 && mBaiduPlayer.getCurrentPosition() < mBaiduPlayer.getDuration()) {
                addViewHistory(mBaiduPlayer.getCurrentPosition());
            }
        }
    }

    protected void addViewHistory(long position) {
        VideoSeekKit.addHisSeek("" + articleItem.getId(), position);
    }

    public String mp4Data;


    public void success(ArticleItemReciver data) {
        if (data.state && data.articleItem != null) {
            articleItem = data.articleItem;
            ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());
            CDPTrackReportManager.getInstance().setCurrentPageName(articleItem.getTitle());
//            if (articleItem.getIsComment().equals("0")) {
//                isComment = articleItem.getIsComment();
//                orderView();
//            }
            sendExposureEvent();
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            articleItem.mShowSwitch = showSwitch;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }

            if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                initDetailFragment(data, true);
                //  videoPayUtil.showPaidView();
            } else {
                initDetailFragment(data, false);
                //  videoPayUtil.judgeShowPayView(articleItem);
            }

//            mBaiduPlayer.stop();
//            mBaiduPlayer.setErrorViewVisible(View.GONE);
//            if (articleItem.getTitle() != null) {
//                mBaiduPlayer.showVideoTitleInfo(articleItem.getTitle());
//            }
            setVideoContent(articleItem.getVideo());

        } else {
//            mBaiduPlayer.onExternalError();
        }
        if (!isAddIntegral) {
            isAddIntegral = true;
            startAddIntegralCounter();
        }
    }

    boolean isAddIntegral = false;

    private void startAddIntegralCounter() {

        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
//                Addintegral.addintegral(VideoVodDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });

        //开启视频任务时
        if (openInteval) {
            AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
                @Override
                public void timeoutCallback() {
                    if (articleItem == null) {
                        return;
                    }
                    Addintegral.addintegral(VideoVodDetailActivity.this, articleItem.getId(), 8, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", false, articleItem);
                }
            }, timeInteval,AddIntegralCounter.VideoTask);
        }

    }

    public void hiddBroccoliLayout() {

        broccoliLayout.setVisibility(View.GONE);
        closeStateView();
    }

    String lastPlayUrl = "";

    private void setVideoContent(String videoStr) {
        if (articleItem != null) {
            mBaiduPlayer.setPoster(ImageKitKt.buildUrl(3, articleItem.getLogo()), ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img));
        }
        try {
            JSONObject video = new JSONObject(videoStr);
            String cdn = video.optString("cdnConfigEncrypt");
            String poster = video.optString("poster", "");
//            if (TextUtils.isEmpty(poster)) {
//                mBaiduPlayer.setPoster(articleItem.getLogo(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
//            } else {
//                mBaiduPlayer.setPoster(poster, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);
//            }
            JSONArray tsAddress = VideoAddressGet.getAddress(video);
            if (tsAddress != null) mp4Data = tsAddress.toString();
            XVideoItem videoItem = new XVideoItem(articleItem.getTitle(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);


            for (int i = 0; tsAddress != null && i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                if (line.has("title")) {
                    XVideoBitRate lineItem = new XVideoBitRate();
                    //"https://video.mjh.pladaily.com.cn/0/b81ab1497ae1133dbc41e584912d77aa/2022/10/06/9754841582fd4fcb9e5ea1a43c190f79/9754841582fd4fcb9e5ea1a43c190f79_1080_hls_210852.m3u8"
                    lineItem.setPath(line.optString("url"));
                    lineItem.setTitle(line.optString("title"));
                    lineItem.setCdnEncypt(cdn);
                    if (!TextUtils.isEmpty(lineItem.getPath())) {
                        videoItem.getBitRates().add(lineItem);
                        lastPlayUrl = lineItem.getPath();
                    }
                }

//                if(i == 0){
//                    String url = line.optString("url");
//                    int beginIndex = url.lastIndexOf(".");
//                    String a =  url.substring(0 ,beginIndex);
//                    String b =  url.substring(beginIndex);
//                    XVideoBitRate bitRate = new XVideoBitRate(""+articleItem.getTitle(),a+"_1"+b,null);
//                    mBaiduPlaye
//
//                    r.setDolbySwitchViewState(false,bitRate);
//                }
            }

            mBaiduPlayer.addVideoItemReverse(videoItem, "源码", true);
            if (DeviceUtils.isCus(this)) {
                mBaiduPlayer.setDolbySwitchViewState(true, null);
            }
            //视频详情类型 并且未缓存过
            if(articleItem.getType() == 5 && videoItem.getBitRates().size() > 0 && !XPlayerPreloadManager.getInstance(this).isPreloaded(videoItem.getBitRates().get(videoItem.getBitRates().size() - 1).getPath())){
                XPlayerPreloadManager.getInstance(this).addPreloadTask(videoItem.getBitRates().get(videoItem.getBitRates().size() - 1).getPath());
            }

            if (videoItem.getBitRates().size() > 0) {
                setVideoPlayerData();
            } else {
                mBaiduPlayer.onExternalError();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());
//            mBaiduPlayer.onExternalError();
        }
    }

    boolean hadAdded = false;

    protected void initDetailFragment(ArticleItemReciver data, boolean appfacBuy) {
        if (hadAdded)
            return;
        Bundle args = new Bundle();
        //ArticleItem nItem = ArticleItem.parse(data.articleItem.orginDataObject);
        //   nItem.setContent(null);
        args.putParcelable("data", data.articleItem);
        args.putParcelable("catalog", catalogItem);
        args.putBoolean("appfacBuy", appfacBuy);
        args.putParcelableArrayList("components", data.components);
        fragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.vodBottomContent, fragment);
        transaction.show(fragment);
        transaction.commitAllowingStateLoss();
        hadAdded = true;

        readStatus();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == MemberActivity.REQUEST_CODE && intent != null
                && intent.getBooleanExtra(MemberActivity.REQUEST_KEY, false)) {
            //  videoPayUtil.judgeShowPayView(articleItem);
        }
    }

    ReadStatusInvoker readStatusInvoker;

    boolean isSendRead = false;

    public void readStatus() {
        if (!isSendRead) {
            readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
                @Override
                public void success(ReadDataReciver data) {
                    AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
//                Message msg = new Message();
//                msg.what = 100;
//                msg.arg1 = (int) data.reads;
//                handler.sendMessageDelayed(msg, 2000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            fragment.setVideoReades((int) data.reads);
                        }
                    });
                }

                @Override
                public void fault(Object data) {
                    AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
                }
            });
            readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
            isSendRead = true;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        launchTimeLong = System.currentTimeMillis();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    public boolean isShowNetWorDialog() {

        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isGoOtherPage) {
            if (!isPlayBeforePause)
                mBaiduPlayer.resume();
            isGoOtherPage = false;
        }
    }

    @Override
    public void noNetwork() {



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TXReportManager.getInstance().app_jhapp_content_detail_interact("退出浏览",
                (isCompleted) ? "是" : "否",
                String.valueOf((stopPosition - startPosition)/1000),
                articleItem,
                (System.currentTimeMillis()-launchTimeLong)/1000,
                null,
                null,
                null,
                null,
                null,
                null,
                PlayerUtils.stringForTime((int) stopPosition));
    }


    public void getVideoDetail() {
        Map<String, String> map = new HashMap();
        map.put("client", "android");
        CatalogItem catalogItem = getIntent().getParcelableExtra("catalog");
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
            String nid = getIntent().getStringExtra("navigate_id");
            if (nid == null) {
                nid = "";
            }
            catalogItem.setCatid(nid);
        }
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        if (!TextUtils.isEmpty(navigate_id)) {
            map.put("navigate_id", "navigate_id");
        }
        map.put("no_content", "1");
        DataInvokeUtil.ziMeiTiApi
                .getArticleById("" + articleItem.getId(), map)
                .map(new Function<Response<JSONObject>, ArticleItemReciver>() {
                    @Override
                    public ArticleItemReciver apply(Response<JSONObject> jsonObjectResponse) throws Exception {
                        ArticleItemReciver articleItemReciver = new ArticleItemReciver();
                        articleItemReciver.readFromJson(jsonObjectResponse.body());
                        return articleItemReciver;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ArticleItemReciver>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ArticleItemReciver articleItemReciver) {
                        success(articleItemReciver);
                    }

                    @Override
                    public void onError(Throwable e) {
//                        mBaiduPlayer.onExternalError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}